#include "hal_function.h"
#include "sht20.h"

#define SHT20_ADDR 0X40

#define SHT20_REG_KEEP_TEMPERATURE 0XE3
#define SHT20_REG_KEEP_HUMIDITY 0XE5
#define SHT20_REG_TEMPERATURE 0XF3
#define SHT20_REG_HUMIDITY 0XF5

SHT20_DataHandle sht20Dadta;

void SHT20_SetStatus(char en,int frq)
{
    sht20Dadta.en = en;
    sht20Dadta.read_frq = frq;
    sht20Dadta.read_cnt = 0;
}


void sht20_process(int arg)
{
    static char shtFsm = 0;

    unsigned char cmd;
    unsigned char data[5] = {0};
    int data16,ret;

    sht20Dadta.read_cnt += arg;
    if(sht20Dadta.en)
    {
        switch(shtFsm)
        {
            case 0:
                if(sht20Dadta.read_cnt >=sht20Dadta.read_frq)
                {
                    sht20Dadta.read_cnt = 0;
                    shtFsm = 0x01;
                }
            break;

            case 0x01:
                sht20Dadta.read_cnt = 0;
                cmd = SHT20_REG_TEMPERATURE;
                ret = i2c_write(SHT20_ADDR,&cmd,1);
                shtFsm = 0x02;
            break;

             case 0x02:
                if(sht20Dadta.read_cnt >= 150)
                {
                    sht20Dadta.read_cnt = 0;
                    ret = i2c_read(SHT20_ADDR,data,3);
                    data16 = data[0];
                    data16 = (data16 << 8) + data[1];
                    data16 &= 0xfffc;
                    sht20Dadta.temperature = data16*(175.72/65536.0) - 46.85;
                    shtFsm = 0x03;
                }
            break;

            case 0x03:
               if(sht20Dadta.read_cnt >= 50)
               {
                   shtFsm = 0x04;
               }
            break;

            case 0x04:
                sht20Dadta.read_cnt = 0;
                cmd = SHT20_REG_HUMIDITY;
                ret = i2c_write(SHT20_ADDR,&cmd,1);
                shtFsm = 0x05;
            break;

            case 0x05:
                if(sht20Dadta.read_cnt >= 150)
                {
                    sht20Dadta.read_cnt = 0;
                    ret = i2c_read(SHT20_ADDR,data,3);
                    data16 = data[0];
                    data16 = (data16 << 8) + data[1];
                    data16 &= 0xfffc;
                    sht20Dadta.humidity = data16*(125.0/65536.0) - 6;
                    shtFsm = 0;
                    //ESP_LOGI("sht20", "the current temperature is %f, humidity is %d",sht20Dadta.temperature,sht20Dadta.humidity);
                }
            break;
        }
    }
}



